package server

import (
	"errors"
	"learning-pass/common/models/mysql"
	"learning-pass/common/proto/user"
	"math/rand"
	"strconv"
	"time"
)

func Login(in *user.LoginReq) (*user.LoginResp, error) {
	u := &mysql.User{}
	username, err := u.FindUserByUsername(in.Username)
	if err != nil {
		return nil, errors.New("用户账号查询失败")
	}
	if username.ID == 0 {
		return nil, errors.New("用户未注册，请前往注册")
	}
	if in.Password != username.Password {
		return nil, errors.New("密码错误")
	}
	return &user.LoginResp{Greet: int64(username.ID)}, nil
}
func Register(in *user.RegisterReq) (*user.RegisterResp, error) {
	u := &mysql.User{}
	username, err := u.FindUserByUsername(in.Username)
	if err != nil {
		return nil, errors.New("用户查询失败")
	}
	if username.ID != 0 {
		return nil, errors.New("用户已经注册")
	}
	tx := mysql.DB
	tx.Begin()
	_, err = u.CreateUser(in)
	if err != nil {
		tx.Rollback()
		return nil, errors.New("注册失败")
	}
	//c := &mysql.Coupon{}
	//s := time.Hour.String()
	//err = c.CreateCoupon("满100减5", s, int64(us.ID))
	//if err != nil {
	//	tx.Rollback()
	//	return nil, errors.New("优惠卷添加失败")
	//}
	tx.Commit()
	return &user.RegisterResp{Greet: "注册成功"}, nil

}
func AddUserStudyPlan(in *user.AddUserStudyPlanReq) (*user.AddUserStudyPlanResp, error) {
	c := &mysql.Course{}
	s := &mysql.StudyPlan{}
	name, err := c.FindCourseByCourseName(in.Course)
	if err != nil {
		return nil, errors.New("课程名称查询失败")
	}
	if name.ID == 0 {
		return nil, errors.New("没有该课程")
	}
	err = s.AddStudyPlan(in)
	if err != nil {
		return nil, errors.New("学习计划添加失败")
	}
	return &user.AddUserStudyPlanResp{Greet: "添加成功"}, nil
}
func DelUserStudyPlan(in *user.DelUserStudyPlanReq) (*user.DelUserStudyPlanResp, error) {
	s := &mysql.StudyPlan{}
	id, err := s.FindStudyPlanById(in.StudyPlanId)
	if err != nil {
		return nil, errors.New("学习计划查询失败")
	}
	if id.ID == 0 {
		return nil, errors.New("该学习计划不存在")
	}
	err = s.DelStudyPlan(in.UserId, in.StudyPlanId)
	if err != nil {
		return nil, errors.New("删除失败")
	}
	return &user.DelUserStudyPlanResp{Greet: "删除成功"}, nil

}
func CreateOrder(in *user.CreateOrderReq) (*user.CreateOrderResp, error) {
	o := &mysql.Order{}

	orderSn := time.Now().String() + strconv.Itoa(rand.Intn(8))
	err := o.CreateOrder(orderSn, float64(in.Price), in.CourseId, in.UserId)
	if err != nil {
		return nil, err
	}
	return &user.CreateOrderResp{Greet: "创建成功"}, nil
}
